import axios from 'axios'
import { ElNotification, type NotificationHandle } from 'element-plus'

const gameAxios = axios.create({
  baseURL: import.meta.env.VITE_APP_GAME_SERVER_URL,
  timeout: 1000 * 6
})

// 单例通知，防止重复弹出：类型判断为any
let notificationInstance: NotificationHandle | null = null

// 添加请求拦截器
gameAxios.interceptors.request.use(
  (config) => {
    return config
  },
  (error) => {
    console.log(error)
    return Promise.reject(error)
  }
)

// 添加响应拦截器
gameAxios.interceptors.response.use(
  (response) => {
    return response
  },
  (error) => {
    // 错误提示：仅弹出一次通知
    if (!notificationInstance) {
      notificationInstance = ElNotification({
        title: '网络错误',
        message: error.message,
        type: 'error',
        onClose() {
          notificationInstance = null
        }
      })
    }
    console.log(error)
    return Promise.reject(error)
  }
)

export default gameAxios
